import React, { Component } from 'react';
import { Button, Modal, Form, Drawer, Alert, Divider } from 'antd';
import '@/assets/css/settings';
import * as DingTalkSettingsService from '../../../axios/DingTalkSettings'
import * as ProductionOrderService from '../../../axios/ProductionOrder'
import * as APIServiceYQ from '../../../axios/api_yq'
import * as BillManageService from '../../../axios/BillManage'
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout';
import { BasicPagination, isInvalidObject, TableCustomize, openSuccessModal, openModalMessage, compareDate, compareString } from '../../../components/TableCustomize'
import { ReportList, ErrorList, ResultList } from '../../../utils/global'
import { getDateHHMMYY_HHMMSS, randomString } from '../../../utils/action'
import SearchForm from './SearchForm';
import AddForm from './AddForm';
import { withRouter } from 'react-router';
import { withPermission } from '../../../components/withpermission'
const CreateButton = withPermission(Button, 'plus')
const DownLoadButton = withPermission(Button, 'download')

class AssemblyAbnormal extends Component {
  state = {
    loading: false,
    dataSource: [],
    searchItem: {
      department: localStorage.getItem('workShop')
    },
    advanced: false,
    formData: {},
    pageSize: 10,
    pageNum: 1,
    total: 0,
    columns: [
      {
        title: '序号',
        dataIndex: 'dataIndex',
        width: 50,
        align: 'center',
        render: (text, record, index) => <span>{(this.state.pageNum - 1) * (this.state.pageSize) + index + 1}</span>
      },

      {
        title: '报告类别',
        width: 100,
        // allowEllipsis: true,
        dataIndex: 'reportType',
        sorter: (a, b) => compareString(a.reportType, b.reportType)
      },
      {
        title: '车间',
        width: 130,
        // allowEllipsis: true,
        dataIndex: 'department',
        sorter: (a, b) => compareString(a.department, b.department)
      },
      {
        title: '机型',
        width: 180,
        dataIndex: 'model',
        sorter: (a, b) => compareString(a.model, b.model),
        // editable: true
      },
      {
        title: '批号',
        dataIndex: 'batchNo',
        width: 100,
        sorter: (a, b) => compareString(a.batchNo, b.batchNo)
      },
      // {
      //   title: '装配机号',
      //   width: 100,
      //   // allowEllipsis: true,
      //   dataIndex: 'assembleProcess',
      //   sorter: (a, b) => compareString(a.assembleProcess, b.assembleProcess)
      // },
      {
        title: '装配开始时间',
        width: 150,
        // allowEllipsis: true,
        dataIndex: 'assembleStartTime',
        sorter: (a, b) => compareString(a.assembleStartTime, b.assembleStartTime)
      },
      {
        title: '第一交机日期',
        width: 150,
        dataIndex: 'firstDeliveryTime',
        ellipsis: true,
        sorter: (a, b) => compareDate(a.firstDeliveryTime, b.firstDeliveryTime)
      },
      {
        title: '第一出机日期',
        width: 150,
        dataIndex: 'firstOutputTime',
        ellipsis: true,
        sorter: (a, b) => compareDate(a.firstOutputTime, b.firstOutputTime)
      },
      {
        title: '异常原因',
        width: 100,
        dataIndex: 'abnormalMsg',
        sorter: (a, b) => compareString(a.abnormalMsg, b.abnormalMsg)
      },
      {
        title: '审批结果',
        width: 100,
        dataIndex: 'isResult',
        sorter: (a, b) => compareString(a.isResult, b.isResult),
        render: (text) => {
          let a = ResultList.find(e => e.id == text)
          return a?.value
        }
      },
      {
        title: '操作',
        width: 100,
        dataIndex: 'opts',
        render: (text, record) => <>
          <a onClick={() => this.openDetails(record)}>详情</a>
          {
            // record.isResult != 1 && record.isResult != 2 ?
            <>
              <Divider type='vertical' />
              <a onClick={() => this.onSubmitFlow(record)}>审批</a>
            </>
            // : null
          }

        </>
      },
      { dataIndex: '' }
    ],
    selectedRows: [],
    selectedRowKeys: [],
    batchNoList: [],     // 批号列表
    departmentList: [],  // 车间数据
    drawerVisible: false,
    loading_submit: false,
  };
  componentDidMount() {
    this.init()
    if (this.props.location.data) {
      this.setState({ searchItem: this.props.location.data }, this.fetch)
    } else {
      this.fetch()
    }
  }
  componentWillUnmount() {
    this.setState = () => {
      return;
    };
  }
  // 初始化查询
  init = () => {
    // 派工班组查询
    ProductionOrderService.findGroupAll().then(res => {
      const departmentList = res.data.data
      this.setState({ departmentList });
    })
    // 派工班组查询
    APIServiceYQ.queryByCondition3({
      "pageNum": 1,
      "pageSize": 1000,
    }).then(res => {
      const batchNoList = res.data.data.data
      this.setState({ batchNoList });
    })
  }

  //初始化加载数据
  fetch = (pageNum = 1, pageSize = 100) => {
    this.setState({ loading: true })
    const { searchItem } = this.state
    searchItem.pageNum = pageNum
    searchItem.pageSize = pageSize
    BillManageService.findAbnormalAll(searchItem).then(res => {
      this.setState({ loading: false })
      if (res.data.data.code !== 200) {
        openModalMessage('warning', res.data.data.msg)
        return
      }
      this.setState({ dataSource: res.data.data.data, total: res.data.data.total, pageNum, pageSize })
    }).catch(err => {
      this.setState({ loading: false })
      openModalMessage('error', err.message)
    })
  }

  handleCancel = e => {
    this.formDrawer && this.formDrawer.resetFields();
    this.setState({
      selectedRowKeys: [],
      selectedRows: [],
      loading_submit: false,
      drawerVisible: false,
    });
    this.fetch();
  };
  add = () => {
    this.setState({ drawerVisible: true })
  }

  onHandleOk = () => {
    console.log('add');
    this.formDrawer.validateFields(async (err, value) => {
      if (err) return;
      this.setState({ loading_submit: true });

      value.assembleStartTime = value.assembleStartTime && getDateHHMMYY_HHMMSS(value.assembleStartTime)
      value.firstOutputTime = value.firstOutputTime && getDateHHMMYY_HHMMSS(value.firstOutputTime)
      value.firstDeliveryTime = value.firstDeliveryTime && getDateHHMMYY_HHMMSS(value.firstDeliveryTime)

      value.createrId = localStorage.getItem('userId')

      console.log(value, '新增******************');
      await BillManageService.addAbnormal(value).then(res => {
        this.setState({ loading_submit: false })
        if (res.data.code !== 200) {
          openModalMessage('warning', res.data.msg);
          return;
        }
        openSuccessModal(res.data.msg);
        this.handleCancel();
      }).catch(err => {
        this.setState({ loading_submit: false });
        openModalMessage('error', err.message);
        return;
      })
    })
  }

  // 审批
  onSubmitFlow = (record) => {
    console.log(record, 'onSubmitFlow');
    const that = this;
    Modal.confirm({
      title: '提示',
      content: '确认发起钉钉审批？',
      onOk: async () => {
        await BillManageService.abnormalApplyNail(`assemblyReportId=${record.id}&userId=${localStorage.getItem('userId')}`).then(res => {
          if (res.data.code !== 200) {
            openModalMessage('warning', res.data.msg);
            return;
          }
          openSuccessModal(res.data.msg);
          that.fetch()
        }).catch(err => {
          that.setState({ loading: false })
          openModalMessage('error', err.message)
        })
      }
    })
  }

  handleSearch = value => {
    console.log(value)
    this.setState({ searchItem: value }, this.fetch);
  };

  onHandleAdvanced = () => {
    this.setState({ advanced: !this.state.advanced })
  }
  loadData = (value, dataSource) => {
    console.log(value, dataSource)
  }
  // 选择某一行数据
  chooseRow = record => {
    let flag = true;
    let index = 0;
    this.state.selectedRowKeys.forEach((row, i) => {
      if (row === record.id) {
        flag = false;
        index = i;
      }
    })
    const selectedRowKeys = this.state.selectedRowKeys;
    const selectedRows = this.state.selectedRows;
    if (flag) {
      selectedRowKeys.push(record.id);
      selectedRows.push(record);
    } else {
      selectedRowKeys.splice(index, 1);
      selectedRows.splice(index, 1);
    }
    this.setState({ selectedRowKeys: selectedRowKeys, selectedRows: selectedRows });
  };

  downloadFather = () => {
    const { selectedRows } = this.state;
    // if (selectedRows.length) {
    //   this.setState({ downloadLoading: true });
    //   BillManageService.exportTestMachineManageExcel({ list: selectedRows }).then(res => {
    //     //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
    //     let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
    //     // 创建A标签
    //     let link = document.createElement('a')
    //     link.style.display = 'none'
    //     link.href = url
    //     // 设置的下载文件文件名
    //     const fileName = decodeURI('试机管理');
    //     // 触发点击方法
    //     link.setAttribute('download', fileName)
    //     document.body.appendChild(link)
    //     link.click()
    //     this.setState({ downloadLoading: false })
    //   })
    // } else {
    //   Modal.confirm({
    //     title: '默认导出数据较多，需要较长时间，确认全部导出吗？',
    //     onOk: async () => {
    //       await this.fetchAll();
    //       const { dataSourceAll } = this.state;
    //       await BillManageService.exportTestMachineManageExcel({ list: dataSourceAll }).then(res => {
    //         //设置下载文件类型为xlsx 不同的类型type也不一样，创建URL对象
    //         let url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
    //         // 创建A标签
    //         let link = document.createElement('a')
    //         link.style.display = 'none'
    //         link.href = url
    //         // 设置的下载文件文件名
    //         const fileName = decodeURI('试机管理');
    //         // 触发点击方法
    //         link.setAttribute('download', fileName)
    //         document.body.appendChild(link)
    //         link.click()
    //         this.setState({ downloadLoading: false })
    //       })
    //     },
    //     onCancel() { }
    //   })
    // }
  }
  fetchAll = async () => {
    const { searchItem, total } = this.state
    searchItem.pageNum = 1
    searchItem.pageSize = total
    // let str = ''
    // for (var key in searchItem) {
    //   if (searchItem[key] || searchItem[key] === 0) {
    //     str += `&${key}=${searchItem[key]}`
    //   }
    // }
    await BillManageService.findAbnormalAll(searchItem).then(res => {
      if (res.data.data.code !== 200) {
        openModalMessage('warning', res.data.data.msg)
        return
      }
      const dataSourceAll = res.data.data.data
      const selectedRowKeys = dataSourceAll.map(item => item.id);
      this.setState({ dataSourceAll, selectedRowKeys, selectedRows: dataSourceAll })
    }).catch(err => {
      openModalMessage('error', err.message)
    })
  }
  // 打开详情页
  openDetails = (record) => {
    const { searchItem } = this.state;

    DingTalkSettingsService.approvalInstanceDetails(record.processInstanceId).then(res => {
      if (res.data.code !== 200) {
        openModalMessage('warning', res.data.msg);
        return;
      }
      let detailForm = res.data.data
      let processInstance = detailForm?.processInstance
      localStorage.setItem('AssemblyAbnormal_searchItem', JSON.stringify(searchItem));
      localStorage.setItem('AssemblyAbnormal_detailList', JSON.stringify({ processInstance, record }));
      this.props.history.push({ pathname: "/AssemblyAbnormal_Details", data: { detailForm, searchItem } })
    }).catch(err => {
      this.setState({ loading_submit: false });
      openModalMessage('error', err.message);
      return;
    })


  }
  resetForm = () => {
    this.formSearch && this.formSearch.resetFields();
    this.setState({
      searchItem: {
        department: localStorage.getItem('workShop')
      }
    }, this.fetch);
  }
  render() {
    const { drawerVisible, loading_submit, advanced, departmentList, batchNoList, loading, dataSource, columns, pageNum, pageSize, total, selectedRowKeys, downloadLoading, searchItem } = this.state;
    const rowSelection = {
      type: 'checkbox',
      selectedRowKeys: selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRows: selectedRows,
          selectedRowKeys: selectedRowKeys,
        })
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        const keys = [... this.state.selectedRowKeys];
        const rows = [... this.state.selectedRows];
        if (selected) {
          changeRows.forEach(row => {
            if (isInvalidObject(keys.find(key => key === row.id))) {
              keys.push(row.id);
              rows.push(row);
            }
          })
        } else {
          changeRows.forEach(row => {
            keys.splice(keys.indexOf(row.id), 1);
            rows.splice(rows.indexOf(row), 1);
          })
        }
        this.setState({ selectedRows: rows, selectedRowKeys: keys })
      }
    }
    return (
      <div>
        <BasicLayoutSearch>
          <SearchForm onSearch={this.handleSearch}
            onClick={this.onHandleAdvanced}
            advanced={advanced}
            searchItem={searchItem}
            departmentList={departmentList}
            ErrorList={ErrorList}
            ReportList={ReportList}
            resetForm={this.resetForm}
            ref={node => (this.formSearch = node)}
          />
        </BasicLayoutSearch>
        <BasicLayout buttons={
          [
            <CreateButton key='1' icon="plus" onClick={this.add} />,
            <DownLoadButton key='2' onClick={this.downloadFather} icon="download" loading={downloadLoading} />

            // <Button key={1} type="primary" icon="plus" onClick={this.add}>新增</Button>,
            // // <Button key={2} type="primary" icon="printer">打印</Button>,
            // <Button type="primary" key={7} onClick={this.downloadFather} icon="download" loading={downloadLoading}>导出</Button>,
          ]} name="总装异常报告表" icon="table">
          <Alert message={<div>已选择<span style={{ color: '#fd1818', margin: '0 3px' }}>{selectedRowKeys.length}</span>项</div>} type="info" showIcon style={{ marginBottom: 15 }} />
          <TableCustomize
            columns={columns}
            rowKey={(record) => record.id}
            dataSource={dataSource}
            pagination={false}
            loading={loading}
            allowDrafting={true}
            allowRowEdit
            allowEditable={this.loadData}
            rowSelection={rowSelection}
            onRow={(record, rowKey) => ({
              onClick: this.chooseRow.bind(this, record, rowKey)
            })}
            rowClassName={(record, index) => {
              return (['editable-row', index % 2 === 0 ? 'editable-row' : 'editable-row12'])
            }}
            scroll={{ x: true, y: 600 }}
          />
          <BasicPagination pageNum={pageNum} pageSize={pageSize} total={total} loadData={this.fetch} />
        </BasicLayout>

        {/* 新增 */}

        <Drawer
          width={400}
          visible={drawerVisible}
          title={'新增 - 总装异常报告表'}
          onClose={this.handleCancel}
          maskClosable={false}
          destroyOnClose
        >
          <AddForm
            onOk={this.onHandleOk}
            ref={node => (this.formDrawer = node)}
            onClose={this.handleCancel}
            departmentList={departmentList}
            batchNoList={batchNoList}
            ErrorList={ErrorList}
            ReportList={ReportList}
            ResultList={ResultList}
            uniqueCode={randomString(36)}
          />
          <div
            style={{
              position: 'absolute',
              right: 0,
              bottom: 0,
              width: '100%',
              borderTop: '1px solid #e9e9e9',
              padding: '10px 16px',
              background: '#fff',
              textAlign: 'right',
            }}
          >
            <Button onClick={this.handleCancel} style={{ marginRight: 10 }}>{'取消'}</Button>
            <Button type="primary" onClick={this.onHandleOk} loading={loading_submit}>
              {'确认'}
            </Button>
          </div>

        </Drawer>
      </div>
    );
  }
}
export default Form.create()(withRouter(AssemblyAbnormal));